<!--
登录表单
-->
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import * as service from '../service'
import { setToken } from '@/utils'
import { useUserStore } from '@/stores'

const userStore = useUserStore()

const formState = reactive({
  account: '',
  password: ''
})

const formRef = ref<FormInstance | null>(null)

const rules = {
  account: [{ required: true, message: '请输入账号' }],
  password: [{ required: true, message: '请输入密码' }]
}

async function confirm () {
  const isValidate = await formRef.value?.validate().catch(() => false)
  const [err, token] = await service.login(formState)
  if (!isValidate || err || !token) return
  setToken(token)
  userStore.token = token
  location.reload()
}

defineExpose({ confirm })

</script>

<template>
  <el-form ref="formRef" :model="formState" :rules="rules" size="large">
    <el-form-item prop="account">
      <el-input v-model="formState.account" clearable :prefix-icon="User" />
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="formState.password" show-password clearable :prefix-icon="Lock" />
    </el-form-item>
  </el-form>
</template>

<style lang="less" scoped>
.passwordIcon {
  color: #000;
  cursor: pointer;
}
</style>
